package ldh.im.base.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;

import java.io.InputStream;
import java.util.Properties;

public class RedisUtil {

    private static final String REDIS_CONFIG = "/redis.properties";
    private static Properties REDIS_PROPERTIES;
    private static Jedis jedis = null;

    static {
        try (InputStream inputStream = RedisUtil.class.getResourceAsStream(REDIS_CONFIG)) {
            REDIS_PROPERTIES = new Properties();
            REDIS_PROPERTIES.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Jedis getJedis() {
        String type = getParam("redis.type");
        if (type.equalsIgnoreCase("single")) {
            String host = getParam("redis.host");
            int port = Integer.parseInt(getParam("redis.port"));
            int timeout = Integer.parseInt(getParam("redis.timeout"));
//            String userName = getParam("redis.userName");
            String password = getParam("redis.password");
            int db = Integer.parseInt(getParam("redis.db"));
            if (jedis == null || !jedis.isConnected()) {
                synchronized (RedisUtil.class) {
                    if (jedis == null  || !jedis.isConnected()) {
                        jedis = new Jedis(host, port, timeout);
                        String auth = jedis.auth(password);
                        if (!auth.contains("OK")) {
                            throw new RuntimeException("auth redis failure, msg:" + auth);
                        }
                        jedis.select(db);
                    }
                }
            }
            return jedis;
        }
        return null;
    }

    public static void close() {
        if (jedis != null) {
            jedis.close();
        }
    }

    private static JedisPoolConfig buildPoolConfig() {
        final JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(128);
        poolConfig.setMaxIdle(128);
        poolConfig.setMinIdle(16);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);
        poolConfig.setNumTestsPerEvictionRun(3);
        poolConfig.setBlockWhenExhausted(true);
        return poolConfig;
    }

    private static String getParam(String key) {
        String value = REDIS_PROPERTIES.getProperty(key);
        if (value == null) {
            throw new RuntimeException("缺少参数：" + key);
        }
        return value;
    }
}
